#!/var/py_tmp/Python-3.2.3/Python/python3.2
import socket
import threading

ROBOT = 1
CLIENT = 2

robot = None
class ClientThread(threading.Thread):
    def __init__(self, socket, address):
        self.socket = socket
        self.address = address
        self.cont = True
	self.type = None
        threading.Thread.__init__(self)
 
    def run(self):
	global robot
        print("Started thread..")
        while(self.cont):
            try :
                message = self.fetch_line(self.socket)
                print("Received line: "+message)
                if(message == 0):
                    self.close()
                    break
		elif(message.find('c') == 0):
		    split_msg = message.split()
		    type = int(split_msg)
		    if(type == ROBOT):
			self.type = ROBOT
			robot = self
		    elif(type == CLIENT):
			self.type = CLIENT
		    else:
			self.type = None
                elif(message.find('a') == 0):
                    print("Found a!")
                elif(message.find('b') == 0):
                    print("Found b!")
                elif(message.find('quit') == 0):
                    self.close()
                    break
                try :
                    if(len(message) > 0):
                        print("Sending line: "+message)
                        self.socket.sendall(bytes(message, "utf-8"))
                        self.socket.sendall(bytes("\r\n", "utf-8"))
                except socket.error:
                    print("Send failed!")
                    self.close()
                    break
            except socket.error:
                print("Socket error, quiting..")
                self.close()
        print("Thread ended..")
        
    def close(self):
	global robot
	if(self.type == ROBOT):
	    robot = None
        self.cont = False
        self.socket.close()
        self.socket = None
        
    def fetch_line(self, socket):
       # print("fetching line..")
        line = b''
        c = self.socket.recv(1)
        while ((c != b'\r') & (c != b'\n')):
            line += c
            c = self.socket.recv(1)
       #     print("*"+line.decode("utf-8"))
      #  print("returning")
       # if(c == 0):
       #     return 0
        return line.decode("utf-8") #bytes(line, "utf8")#bytes(,"utf-8")
    
class MiniCuriosityServer:
    def __init__(self, port):
        print("Starting server..")
        print("Creating socket..")
        try:
            self.serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.serversocket.bind(("tuliluikku.com", port))
            self.serversocket.listen(5)
        except(socket.error):
            print(socket.error)
            
        print("Starting to listen..")
        print("")
        threads = []
        while 1:
            (clientsocket, address) = self.serversocket.accept()
            print("Connection accepted, starting a thread..")
            ct = ClientThread(clientsocket, address)
            ct.daemon = True
            ct.start()
      #      ct.join()
            threads.append(ct)
        self.serversocket.close()
        for t in threads:
            t.join()
        sys.exit(0)
        
    

server = MiniCuriosityServer(32212)

